package com.android.manghe.index.fragment

import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.viewpager.widget.PagerAdapter
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import com.android.base.frame.extend.IStateController
import com.android.base.frame.title.ETitleType
import com.android.base.frame.view.XStateController
import com.android.base.tools.DisplayUtil
import com.android.manghe.R
import com.android.manghe.cache.UserHolder
import com.android.manghe.category.adapter.CategoryAuctionGridAdapter
import com.android.manghe.category.model.CategoryInfo
import com.android.manghe.category.presenter.PCategory
import com.android.manghe.common.frame.fragment.MVPWebSocketFragment
import com.android.manghe.common.model.AuctionSocketRes
import com.android.manghe.search.activity.SearchCategoryActivity
import com.android.manghe.user.activity.LoginActivity
import com.android.manghe.view.GridAuctionSpacesItemDecoration
import com.flyco.tablayout.listener.OnTabSelectListener
import com.zhangke.websocket.ErrorResponse
import com.zhangke.websocket.Response
import kotlinx.android.synthetic.main.fragment_category.*
import kotlinx.android.synthetic.main.view_search.*
import java.util.*

class CategoryFragment : MVPWebSocketFragment<PCategory>() , IStateController<XStateController> {
    override fun getStateView(): XStateController {
        return mView.findViewById(R.id.xStateController)
    }

    private val mAdapterList = arrayListOf<CategoryAuctionGridAdapter>()
    private val mRecyclerViewList = arrayListOf<RecyclerView>()

    override fun getLayoutId() = R.layout.fragment_category
    override fun showToolBarType() = ETitleType.SIMPLE_TITLE
    override fun initData(savedInstanceState: Bundle?, parent: View) {
        val searchView = LayoutInflater.from(activity!!).inflate(R.layout.view_search, null, false)
        val searchLayoutParam =
            RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, DisplayUtil.dip2px(activity, 36f))
        searchLayoutParam.addRule(RelativeLayout.CENTER_IN_PARENT)
        searchView.layoutParams = searchLayoutParam
        titleBar.addCenterView(searchView)
            .setBackgroundColor(ContextCompat.getColor(activity!!, R.color.white))
        initListener()
        p.getCategories()
    }
    private fun initListener() {
        tvSearch.setOnClickListener {
            if(UserHolder.getUserInfo(activity) != null) {
                //进入搜索页面
                SearchCategoryActivity.showActivity(activity!!)
            }else{
                open(LoginActivity::class.java)
            }
        }
        tabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                p.setTabPosition(position)
                showRecyclerView(position)
            }

            override fun onTabReselect(position: Int) {
            }
        })
    }

    override fun onMessageResponse(message: Response<*>) {
        p.dealSocketData(message.responseText)
    }

    override fun onSendMessageError(error: ErrorResponse) {
        p.loadGridData()
    }

    fun updateTabs(categoryList: List<CategoryInfo>) {
        createRvs(categoryList.size)
        tempViewPager.adapter = object : PagerAdapter() {
            override fun isViewFromObject(p0: View, p1: Any): Boolean {
                return p0 == p1
            }

            override fun getCount(): Int {
                return categoryList.size
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                val view = View(activity)
                container.addView(view)
                return view
            }

            override fun getPageTitle(position: Int): CharSequence? {
                return categoryList[position].catname
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                container.removeView(`object` as View)
            }
        }
        tabLayout.setViewPager(tempViewPager)
    }

    fun updateGridData(dataList: List<AuctionSocketRes.ListBean>) {
        mAdapterList[tabLayout.currentTab]?.update(dataList)
        if (dataList.isEmpty()) {
            xStateController.showEmpty()
        } else {
            xStateController.showContent()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        p.stopSocketTimer()
    }

    fun createRvs(size : Int){
        rvContainer.removeAllViews()
        mRecyclerViewList.clear()
        mAdapterList.clear()
        for(i in 0 until size){
            val recyclerView =
                RecyclerView(mContext)
            recyclerView.layoutManager =
                GridLayoutManager(activity, 2)
            recyclerView.addItemDecoration(GridAuctionSpacesItemDecoration(DisplayUtil.dip2px(activity, 8f)))
            recyclerView.itemAnimator = null
            val adapter= CategoryAuctionGridAdapter(
                activity,
                ArrayList<AuctionSocketRes.ListBean>()
            )
            recyclerView.adapter = adapter
            mAdapterList.add(adapter)
            mRecyclerViewList.add(recyclerView)
            rvContainer.addView(recyclerView)
            recyclerView.visibility = if(i == 0) View.VISIBLE else View.GONE
        }
    }

    fun showRecyclerView(position: Int){
        for(rv in mRecyclerViewList){
            rv.visibility = View.GONE
        }
        mRecyclerViewList[position].visibility = View.VISIBLE
    }
}
